package com.tous.cloud.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author mengwei
 * @description GrayReleaseFilter
 * @createDate 2025/7/21 17:14
 */
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class GrayReleaseFilter implements GlobalFilter {

    private static final String GRAY_RELEASE_ATTRIBUTE = "grap-tag";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String version = request.getHeaders().getFirst(GRAY_RELEASE_ATTRIBUTE);

        if ("true".equals(version)) {
            // 添加灰度标记
            exchange.getAttributes().put(GRAY_RELEASE_ATTRIBUTE, true);
        }

        return chain.filter(exchange);
    }

}
